package org.usmile.algorithms.learn.graph;

import java.util.ArrayList;
import java.util.List;

public class AdjMatrix implements Graph {
    private final int v;
    private final int[][] adj;

    private int e;

    public AdjMatrix(int v) {
        this.v = v;
        this.adj = new int[v][v];
    }

    @Override
    public int getV() {
        return this.v;
    }

    @Override
    public int getE() {
        return this.e;
    }

    @Override
    public void addEdge(int w, int v) {
        if (w == v || w >= this.v || v >= this.v) {
            return;
        }
        adj[w][v] = adj[v][w] = 1;
        e++;
    }

    @Override
    public boolean hasEdge(int w, int v) {
        if (w >= this.v || v >= this.v) {
            return false;
        }

        return adj[w][v] == 1;
    }

    @Override
    public List<Integer> adj(int v) {
        if (v >= this.v) {
            return new ArrayList<>();
        }

        List<Integer> result = new ArrayList<>();
        for (int i = 0; i < this.v; i++) {
            if (adj[v][i] == 1) {
                result.add(i);
            }
        }

        return result;
    }

    @Override
    public int degree(int v) {
        return adj(v).size();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("顶点数 = %d，边数 = %d \n", v, e));
        for (int i = 0; i < v; i++) {
            sb.append("·");
            for (int j = 0; j < v; j++) {
                sb.append(adj[i][j]).append("·");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        AdjMatrix adjMatrix = new AdjMatrix(8);
        adjMatrix.addEdge(0, 1);
        adjMatrix.addEdge(1, 2);
        adjMatrix.addEdge(3, 2);
        System.out.println(adjMatrix.adj(1));
        System.out.println(adjMatrix);
    }
}